package com.telit.common.util;

import com.telit.common.vo.MenuTreeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Auther amy
 * @Describe 树状图工具类
 */
public class TreeUtils {

    private static Logger log = LoggerFactory.getLogger(TreeUtils.class);

    public static List<MenuTreeVO> listWithTree(List<MenuTreeVO> menuList) {
        List<MenuTreeVO> result = menuList;
        //1.组装成父子分类
        //2.找到所有的一级分类（父分类ID为0）
        List<MenuTreeVO> levelOneMenu = result.stream()
                .filter(authorities -> authorities.getParentId() == 0)
                .peek(authorities ->
                        authorities.setChildren(getChildrens(authorities,result))
                )
                .sorted(Comparator.comparingInt(menu -> (menu.getMenuSort() == null ? 0 : menu.getMenuSort())))
                .collect(Collectors.toList());
        return levelOneMenu;
    }

    private static List<MenuTreeVO> getChildrens(MenuTreeVO menuTreeVO,List<MenuTreeVO> menuTreeVOList){
        List<MenuTreeVO> childrens = menuTreeVOList.stream()
                .filter(a -> a.getParentId().intValue() == menuTreeVO.getId().intValue())
                .map(a -> {
                            a.setChildren(getChildrens(a,menuTreeVOList));
                            return a;
                        }
                )
                .sorted(Comparator.comparingInt(menu -> (menu.getMenuSort() == null ? 0 : menu.getMenuSort())))
                .collect(Collectors.toList());
        return childrens;
    }


}
